<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Agency extends Model
{
    /**
     * @var array
     */
    protected $fillable = ['name', 'type_id', 'province_id', 'province', 'admin_id', 'registered_at'];

    public static function add($data)
    {
        DB::beginTransaction();
        try {
            /* 添加角色 */
            $adminData = [
                'username' => $data['username'],
                'password' => bcrypt($data['password']),
                'status' => 1
            ];
            $adminModel = Admin::create($adminData);

            if (!$adminModel) {
                throw new \Exception('');
            }

            $adminModel->adminRoles()->create(['role_id' => 2]);

            $data['admin_id'] = $adminModel->id;
            if (!self::create($data)) {
                throw new \Exception('');
            }

            DB::commit();
            return true;
        } catch (\Exception $e) {

            Log::error($e->getMessage());
            DB::rollBack();
            return false;
        }
    }

    /**
     * @param $data
     * @return bool
     * @author zhuang<pingguoli@gmail.com>
     * @Date 2020/6/28 下午3:51
     */
    public function edit($data)
    {
        DB::beginTransaction();
        try {
            if (!$this) {
                throw new \Exception('');
            }
            /* 编辑角色 */
            $this->update($data);

            if (!empty($data['password'])) {
                $this->admin()->update(['password' => bcrypt($data['password'])]);
            }

            DB::commit();
            return true;
        } catch (\Exception $e) {

            Log::error($e->getMessage());
            DB::rollBack();
            return false;
        }
    }

    public function delete()
    {

        DB::beginTransaction();
        try {
            if (!$this) {
                throw new \Exception('');
            }

            if (!$this->admin->adminRoles()->delete()) {
                throw new \Exception('adminRoles');
            }

            if (!$this->admin()->delete()) {
                throw new \Exception('admin');
            }

            if (!parent::delete()) {
                throw new \Exception('parent');
            }

            DB::commit();
            return true;
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            DB::rollBack();
            return false;
        }
    }

    public function admin()
    {
        return $this->belongsTo(Admin::class);
    }

    public function users()
    {
        return $this->hasMany(User::class);
    }

    public function type()
    {
        return $this->belongsTo(Type::class);
    }

    public function devices()
    {
        return $this->hasMany(Device::class);
    }
}
